import { createRouter, createWebHistory } from 'vue-router'
import Echarts from '@/views/Echarts'
import User from '@/views/Member'
import Table from '@/views/Table'
import Task from '@/views/task/Task'
import Progress from '@/views/progress/Progress'
import Layout from "@/layout/Layout";


const routes = [
  {
    path: '/',
    name: 'layout',
    meta: {
      requiresAuth: true
    },
    component: Layout,
    redirect: '/table',
    children: [
      {
        path: '/echarts',
        name: 'echarts',
        component: Echarts,
      },
      {
        path: '/table',
        name: 'table',
        component: Table,
      },
      {
        path: '/task',
        name: 'task',
        component: Task,
      },
      {
        path: '/progress',
        name: 'progress',
        component: Progress,
      },
      {
        path: '/user',
        name: 'user',
        component: User,
      },
      {
        path: '/task/:id',
        name: 'TaskView',
        component:() => import("@/views/task/TaskView")
      },
      {
        path: '/progress/:id',
        name: 'ProgressView',
        component:() => import("@/views/progress/ProgressView")
      },
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import("@/views/Login"),
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
router.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem("token")
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      // 需要身份验证的路由，并且token为null，则跳转到登录页面
      next({
        path: '/login',
        query: {redirect: to.fullPath}
      })
    } else {
      next() // 确保一定要调用 next()
    }
  }else {
    next()
  }
})

export default router
